package com.gmrz.uap.model;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class _BuildDatabaseJS {
    private List<TableMeta> tableMetaList;
    private String databaseJsPath;

    public _BuildDatabaseJS(List<TableMeta> tableMetaList, String databaseJsPath) {
        this.tableMetaList = tableMetaList;
        this.databaseJsPath = databaseJsPath;
    }

    public void build() throws IOException {
        StringBuffer sb = new StringBuffer();
        sb.append("var DBConts=");
        JSONObject rootJson = new JSONObject();
        for (TableMeta tableMeta : tableMetaList) {
            JSONObject tableJson = new JSONObject();
            String tableName = "TABLE_" + tableMeta.name.toLowerCase().replaceFirst("t_", "").toUpperCase();

            for (ColumnMeta columnMeta : tableMeta.columnMetas) {
                tableJson.put(columnMeta.name.toUpperCase(), columnMeta.name);
            }
            rootJson.put(tableName, tableJson);
        }

        sb.append(rootJson.toString());

        IOUtils.write(sb.toString(), new FileOutputStream(new File(databaseJsPath)), "utf-8");
    }
}
